package com.tempjob.common.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hui
 * @Date 2024/3/9 下午3:06
 **/
@Configuration
public class RestTemplateConfig {

    //最大连接数
    @Value("${http.maxTotal:200}")
    private Integer maxTotal;

    //并发数
    @Value("${http.defaultMaxPerRoute:50}")
    private Integer defaultMaxPerRoute;

    //创建连接的最长时间
    @Value("${http.connectTimeout:30000}")
    private Integer connectTimeout;

    //从连接池中获取到连接的最长时间
    @Value("${http.connectionRequestTimeout:30000}")
    private Integer connectionRequestTimeout;

    //数据传输的最长时间
    @Value("${http.socketTimeout:30000}")
    private Integer socketTimeout;

    //提交请求前测试连接是否可用
    @Value("${http.staleConnectionCheckEnabled:true}")
    private boolean staleConnectionCheckEnabled;

    //可用空闲连接过期时间,重用空闲连接时会先检查是否空闲时间超过这个时间，如果超过，释放socket重新建立
    @Value("${http.validateAfterInactivity:60000}")
    private Integer validateAfterInactivity;

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
        // 获取现有的消息转换器
        List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
        // 添加FastJson消息转换器
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        converters.add(fastJsonConverter);
        return restTemplate;

    }

    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(maxTotal); // 最大连接数
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);    //单个路由最大连接数
        connectionManager.setValidateAfterInactivity(validateAfterInactivity); // 最大空间时间

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)        //服务器返回数据(response)的时间，超过抛出read timeout
                .setConnectTimeout(connectTimeout)      //连接上服务器(握手成功)的时间，超出抛出connect timeout
                .setStaleConnectionCheckEnabled(staleConnectionCheckEnabled) // 提交前检测是否可用
                .setConnectionRequestTimeout(connectionRequestTimeout)//从连接池中获取连接的超时时间，超时间未拿到可用连接，会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
                .build();
        //headers
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
        headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
        headers.add(new BasicHeader("Accept-Language", "zh-CN"));
        headers.add(new BasicHeader("Connection", "Keep-Alive"));
        headers.add(new BasicHeader("Content-type", "application/json;charset=UTF-8"));
        headers.add(new BasicHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"));
        headers.add(new BasicHeader("Cookie","yfx_c_g_u_id_10000057=_ck24091909041019786124751813703; yfx_f_l_v_t_10000057=f_t_1726707850968__r_t_1726707850968__v_t_1726733235683__r_c_0; azSsQE5NvspcO=60EkhvkoifVnhEIHGPR5fj9bZJeDkyhgyXO4GQkGPrLDnU.dMIBrDGELatoXccqtV5rqWVntqDIy4UixTuZPN5oG; yfx_c_g_u_id_10000063=_ck24112617111218257761671435081; arialoadData=false; azSsQE5NvspcS=60O18VlXiBMthkzNV4kc3Tfs0jykuolpt9odwWQ27oHo40c.K37qMJ5RlUq0pl1tSizIPdi601XkJXuLOWrW5OFa; yfx_f_l_v_t_10000063=f_t_1732612272819__r_t_1732957699138__v_t_1732976135813__r_c_1; azSsQE5NvspcP=0FJ50PMyjZyA7QJvT1JdkzIZpDks1grYyi.FSoQ5CKuNRTc_P5DjHp_B0wZ07yhD4Ng1U2qzzKnusnmcveGMqmm4R894lYOHeZVPAvR75lYDPsaI1gEhVtLE7C5WovW80SEkvPkVcWu8EsFIj5I1t3EgiX3qXz3ZD_mN6GJmtxcS9gGoYWbD3tGOMJChf9bPbf6h2CCkFfR8gTDxRVTUd_jkUZSbuTcEYBl2bJnjk87EVbYSBIEUpZiTjFHwveY2ee6t.S4OG3MNBEBUKE8.AopMrOuAcGm0rfP4AfqqUbLGHlX5.qBVZHv2zTCDJqlsww_zVuxSHpTrY6T5O.wnPjFQzT4IQj1gNz033aLQnqJyUUgwWk9OBXgf6dbxFJRMEj8NYzwXkDtjMS2.n9uwyrq"));

        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .setDefaultHeaders(headers)
                // 保持长连接配置，需要在头添加Keep-Alive
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                //重试次数，默认是3次，没有开启
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))
                .build();
    }


}

